package com.threeti.mecool.core.util;

import com.threeti.mecool.core.exception.PreSaveValidateException;

public class ExceptionHelper {
    /**
     * getPreSaveValidateException(root, true)
     */
    public static Exception getPreSaveValidateException(Exception root) {
        return getPreSaveValidateException(root, true);
    }

    public static Exception getPreSaveValidateException(Exception root, boolean nullToRoot) {
        return getCauseTarget(root, PreSaveValidateException.class, nullToRoot);
    }

    public static Exception getCauseTarget(Exception root, Class<? extends Exception> target, boolean nullToRoot) {
        Throwable cause = root;
        while (cause != null && cause.getClass() != target) {
            cause = cause.getCause();
        }
        return ((cause == null || cause.getClass() != target) && nullToRoot) ? root : (Exception) cause;
    }
}
